package http.dtail;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class HttpResponse {
    private String version = "HTTP/1.1";
    private int status;
    private String message;
    private Map<String,String> headers = new HashMap<>();
    // 单独用于存储 cookie 信息
//    private Map<String,String> cookies = new HashMap<>();
    private StringBuilder body = new StringBuilder();
    private OutputStream outPutStream = null;

    public static HttpResponse build(OutputStream outputStream){
        HttpResponse response = new HttpResponse();
        response.outPutStream = outputStream;
        return response;
    }


    public void setVersion(String version) {
        this.version = version;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setHeaders(String key,String value) {
        this.headers.put(key,value);
    }

    public void writeBody(String content) {
        this.body.append(content);
    }
//
//    public void setCookies(String key,String value){
//        cookies.put(key,value);
//    }

    public void flush() throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outPutStream));
        bufferedWriter.write(version +" " + status +" " + message+"\n");
        headers.put("Content-Length",body.toString().getBytes().length+" ");
        for(Map.Entry<String,String> entry : headers.entrySet()){
            bufferedWriter.write(entry.getKey() + ":" + entry.getValue() + "\n");
        }
        bufferedWriter.write("\n");
        bufferedWriter.write(body.toString());
        bufferedWriter.flush();
    }
}
